<template>
	<view class="wrapper">
		<!-- 合同查看器 -->
		<contract-viewer :visible="showContract" :agreements="agreements" @close="handleClose" @confirm="handleContractConfirm" />
		<!-- 顶部价格信息 -->
		<view class="top" v-if="product">
			<view class="top-title">今日购机价格</view>
			<view class="top-main">
				<view class="top-main-name">{{ product.product_name }}</view>
				<view class="top-main-price">{{ defaultSku.purchase_price }}元</view>
			</view>
		</view>

		<view class="main" v-if="product">
			<!-- 商品详情 -->
			<view class="goods">
				<view class="goods-title">商品详情</view>
				<view class="goods-line"></view>

				<view class="goods-item">
					<view class="goods-item-label">商品名称</view>
					<view class="goods-item-value">{{ product.product_name }}</view>
				</view>

				<!-- 动态规格展示 -->
				<view class="goods-item" v-for="spec in product.spec_attr" :key="spec.group_id">
					<view class="goods-item-label">{{ spec.group_name }}</view>
					<view class="goods-item-box">
						<view
							class="goods-item-box-item"
							v-for="item in spec.spec_items"
							:key="item.item_id"
							:class="{
								'goods-item-box-active': selectedSpecIds.includes(item.item_id)
							}"
							@click="selectSpec(item.item_id, spec.group_id)"
						>
							{{ item.spec_value }}
						</view>
					</view>
				</view>

				<view class="goods-item">
					<view class="goods-item-label">出租方式</view>
					<view class="goods-item-value">{{ product.leasing_method }}</view>
				</view>
			</view>

			<!-- 出租方案 -->
			<view class="rentalPlan">
				<view class="rentalPlan-title">出租方案</view>
				<view class="rentalPlan-item" v-for="(plan, index) in rentalPlan" :key="plan.value">
					<view class="rentalPlan-item-left">{{ plan.title }}</view>
					<view class="rentalPlan-item-right">¥{{ plan.value }}</view>
				</view>
				<view class="rentalPlan-item rentalPlan-item_">
					<view class="rentalPlan-item-left rentalPlan-item_-left">购机价格</view>
					<view class="rentalPlan-item-right rentalPlan-item_-right">¥{{ defaultSku.purchase_price }}</view>
				</view>
			</view>

			<!-- 注意事项 -->
			<view class="precautions">
				<view class="precautions-title">注意事项:</view>
				<view class="precautions-content">
					<view class="precautions-content-item">1.您购机成功后，系统将为您自动匹配用户，匹配周期7-30日。</view>
					<view class="precautions-content-item">
						2.匹配期间不产生收益，匹配成功，用户成功签收后开始计算收益。(订单匹配最长时限为30天，超过30天未匹配成功的订单，将自动退回我的背包，您可选择取回或再次委托出租。)请注意，匹配未满30日的商品，无法退回背包。
					</view>
				</view>
				<view class="precautions-text">温馨提示：下单成功，不可更改或取消</view>
			</view>

			<!-- 协议 -->
			<view class="agreement">
				<view class="agreement-content" @click="handleAgree">
					<image class="agreement-content-icon" v-if="agree" src="/package-purse/static/images/xuanzhong1.png" mode="widthFix" />
					<image class="agreement-content-icon" v-else src="/package-purse/static/images/xuanzhong.png" mode="widthFix" />
					我已阅读并同意签署
					<text v-for="item in agreements" @click.stop="agreementClick">《{{item.title}}》</text>
				</view>
			</view>

			<!-- 下单按钮 -->
			<view class="button" @click="$u.debounce(createOrder, 800)">立即下单</view>
		</view>
	</view>
</template>

<script>
import ContractViewer from '@/components/contract-viewer.vue';
import product from '@/api/modules/product';
import { trusteeship } from '@/api';
import { requestPayment } from '@/utils/payment'; // 你的接口文件路径
import { calculateRentalIncome } from '@/utils/common.js';
export default {
	components: {
		ContractViewer
	},
	data() {
		return {
			// 合同相关
			showContract: false,
			agreements: [],
			id: null,
			product: null,
			defaultSku: null,
			selectedSpecIds: [], // 已选规格
			agree: false,
			showAgreement: false,
			orderInfo: null, // 保存订单信息
			isPaying: false, // 防止重复支付
			rentalPlan: [
				{
					title: '预期租金收益',
					value: 0
				},
				{
					title: '预期每月收益',
					value: 0
				},
				{
					title: '预期每日收益',
					value: 0
				}
			]
		};
	},
	onLoad(options) {
		if (options.id) {
			this.id = options.id;
			this.getOrderDetail();
			this.getAgreement()
		}
	},
	watch: {
		'defaultSku.purchase_price'() {
			this.changeProductPlan();
		}
	},
	methods: {
		async getAgreement() {
			const res = await trusteeship.getAgreementList();
			this.agreements = res.data
			console.log('agreements>>>>>>>>>>>',this.agreements);
		},
		changeProductPlan() {
			const userRate = this.product.user_rate;
			const purchasePrice = Number(this.defaultSku.purchase_price);
			try {
				const result = calculateRentalIncome(purchasePrice, userRate, 12);
				this.rentalPlan[0].value = result.totalRentalIncome;
				this.rentalPlan[1].value = result.monthlyIncome;
				this.rentalPlan[2].value = result.dailyIncome;
			} catch (error) {
				console.error('计算失败:', error.message);
			}
		},
		async getOrderDetail() {
			try {
				const res = await product.getProductDetail({ id: this.id });

				if (!res || !res.data) {
					uni.showToast({
						title: '获取商品信息失败',
						icon: 'none'
					});
					return;
				}

				this.product = res.data;

				// 确保 default_sku 存在且有必要的属性
				if (!res.data.default_sku || !res.data.default_sku.spec_sku_id) {
					console.error('商品规格信息不完整', res.data);
					uni.showToast({
						title: '商品规格信息不完整',
						icon: 'none'
					});
					return;
				}

				this.defaultSku = res.data.default_sku;

				// 安全地处理规格ID
				try {
					this.selectedSpecIds = String(res.data.default_sku.spec_sku_id || '')
						.split('_')
						.filter(Boolean) // 过滤掉空字符串
						.map((id) => {
							const num = Number(id);
							return isNaN(num) ? 0 : num; // 确保转换失败时使用0或其他默认值
						});
				} catch (e) {
					console.error('处理规格ID时出错', e);
					this.selectedSpecIds = [];
				}
			} catch (err) {
				console.error('获取商品详情失败', err);
				uni.showToast({
					title: '获取商品信息失败，请重试',
					icon: 'none'
				});
			}
		},
		// 切换规格
		selectSpec(itemId, groupId) {
			try {
				// 先删除同组已选，再添加当前选项
				const specAttr = this.product.spec_attr.find((s) => s.group_id === groupId);

				if (!specAttr || !Array.isArray(specAttr.spec_items)) {
					console.error('规格属性不存在或格式错误', { groupId, specAttr });
					return;
				}

				const groupItemIds = specAttr.spec_items.map((i) => i.item_id);

				// 创建新的选中数组，避免直接修改原数组
				let newSelectedSpecs = this.selectedSpecIds.filter((id) => !groupItemIds.includes(id));
				newSelectedSpecs.push(itemId);

				// 更新选中的规格
				this.selectedSpecIds = newSelectedSpecs;

				// 确保所有规格都已选择才进行SKU匹配
				const allGroupsHaveSelection = this.product.spec_attr.every((group) => this.selectedSpecIds.some((id) => group.spec_items?.some((item) => item.item_id === id)));

				if (allGroupsHaveSelection) {
					// 按照规格组的顺序对选中的规格ID进行排序
					const sortedSpecs = [];
					this.product.spec_attr.forEach((group) => {
						const selectedId = this.selectedSpecIds.find((id) => group.spec_items?.some((item) => item.item_id === id));
						if (selectedId) {
							sortedSpecs.push(selectedId);
						}
					});

					const specKey = sortedSpecs.join('_');
					const sku = this.product.sku_list.find((s) => s.spec_sku_id === specKey);

					if (sku) {
						this.defaultSku = { ...sku }; // 创建新对象确保触发响应式更新
					} else {
						console.warn('未找到匹配的SKU', { specKey, skuList: this.product.sku_list });
					}
				}
			} catch (err) {
				console.error('切换规格时出错', err);
				uni.showToast({
					title: '切换规格失败，请重试',
					icon: 'none'
				});
			}
		},
		agreementClick(e) {
			this.showContract = true;
		},

		// 处理合同确认
		handleContractConfirm(agreement) {
			console.log('已确认协议:', agreement.name);
			this.agree = true;
		},
		handleClose() {
			this.showContract = false;
		},
		handleAgree() {
			if (this.agree) {
				this.agree = false;
			} else {
				this.agreementClick();
			}
		},

		/**
		 * 处理支付
		 */
		async handlePayment(orderData) {
			if (this.isPaying) return;
			this.isPaying = true;

			// 手动解析查询字符串的工具函数（替代URLSearchParams）
			const parseQueryString = (str) => {
				const params = {};
				if (!str) return params;

				// 去除字符串中的引号（支付宝返回结果可能包含引号）
				const cleanStr = str.replace(/"/g, '');
				const pairs = cleanStr.split('&');

				pairs.forEach((pair) => {
					const [key, value] = pair.split('=');
					if (key && value) {
						params[key] = value;
					}
				});
				return params;
			};

			try {
				// 订单唤起支付，获取tradeNO
				const res = await trusteeship.aliPayment({
					order_id: orderData.id
				});

				// 调用支付宝支付
				const [error, payResult] = await uni.requestPayment({
					provider: 'alipay',
					orderInfo: res.data
				});

				console.log('支付结果:', payResult);

				// 判断支付是否成功
				let isSuccess = false;
				let message = '';
				let tradeNo = payResult?.extendInfo?.tradeNo;

				if (error) {
					isSuccess = false;
					message = `支付失败: ${error.errMsg === 'requestPayment:fail' ? '支付过程出错' : error.errMsg || '未知错误'}`;
				} else if (payResult) {
					if (payResult.resultCode === '9000') {
						isSuccess = true;
						message = '支付成功！您已成功完成付款。';

						// 使用自定义工具函数解析result参数
						const resultParams = parseQueryString(payResult.result);
						if (resultParams.success === 'true') {
							console.log('支付结果确认成功，交易号:', resultParams.trade_no);
							tradeNo = tradeNo || resultParams.trade_no;
						}
					} else {
						isSuccess = false;
						let errorText = '';
						switch (payResult.resultCode) {
							case '4000':
								errorText = '支付失败，参数错误';
								break;
							case '6001':
								errorText = '支付已取消，您已放弃付款';
								break;
							case '6002':
								errorText = '网络连接出错，请检查网络后重试';
								break;
							case '6004':
								errorText = '支付结果未知，请查询订单状态';
								break;
							default:
								errorText = payResult.errMsg === 'requestPayment:fail' ? '支付过程出错' : payResult.errMsg || `错误码: ${payResult.resultCode}`;
						}
						message = `支付失败: ${errorText}`;
					}
				}

				// 弹窗提示
				uni.showModal({
					title: isSuccess ? '支付成功' : '支付提示',
					content: message + (tradeNo ? `\n交易号: ${tradeNo}` : ''),
					showCancel: false,
					confirmText: '确定',
					success: (modalRes) => {
						if (modalRes.confirm && isSuccess) {
							uni.navigateBack();
						}
					}
				});
				return { isSuccess, message, tradeNo };
			} catch (err) {
				console.error('支付过程异常:', err);
				uni.showModal({
					title: '支付异常',
					content: '支付过程发生异常，请稍后重试',
					showCancel: false,
					confirmText: '确定'
				});
				return { isSuccess: false, message: '支付过程发生异常', tradeNo: '' };
			} finally {
				this.isPaying = false;
			}
		},
		// 创建订单
		async createOrder() {
			// 检查是否同意协议
			if (!this.agree) {
				uni.showToast({
					title: '请先阅读并同意相关协议',
					icon: 'none'
				});
				this.agreementClick();
				return;
			}

			// 检查商品和SKU信息
			if (!this.product || !this.defaultSku) {
				uni.showToast({
					title: '商品信息不完整',
					icon: 'none'
				});
				return;
			}

			try {
				uni.showLoading({
					title: '创建订单中...',
					mask: true
				});

				// 构建商品规格描述
				const specDesc = this.product.spec_attr
					.map((group) => {
						const selectedItem = group.spec_items.find((item) => this.selectedSpecIds.includes(item.item_id));
						return selectedItem ? `${group.group_name}:${selectedItem.spec_value}` : '';
					})
					.filter(Boolean)
					.join(' ');

				// 调用创建订单接口
				const res = await product.createOrder({
					product_id: this.product.product_id,
					product_sku_id: this.defaultSku.product_sku_id,
					pay_source: 'h5', // 根据实际场景设置
					pay_type: '30', // 默认使用支付宝支付
					product_attr: specDesc
				});

				// 处理订单创建成功后的逻辑
				if (res && res.code === 1) {
					// 保存订单信息
					this.orderInfo = res.data;

					// 调用支付
					await this.handlePayment(res.data);

					uni.showToast({
						title: '正在发起支付...',
						icon: 'loading',
						duration: 1500
					});
				} else {
					throw new Error(res.msg || '创建订单失败');
				}
			} catch (err) {
				console.error('创建订单失败', err);
				uni.showToast({
					title: err.message || '创建订单失败，请重试',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.wrapper {
	padding-bottom: 30rpx;
}
.top {
	padding: 40rpx 30rpx;
	background: #ffffff;
	border-radius: 0rpx 0rpx 25rpx 25rpx;
	&-title {
		font-family: ' PingFang SC';
		font-weight: 400;
		font-size: 30rpx;
		color: #666666;
		margin-bottom: 20rpx;
	}
	&-main {
		display: flex;
		align-items: center;
		justify-content: space-between;
		&-name {
			font-family: 'PingFang SC';
			font-weight: bold;
			font-size: 26rpx;
			color: #333333;
		}
		&-price {
			font-family: 'PingFang SC';
			font-weight: bold;
			font-size: 26rpx;
			color: #ff0000;
		}
	}
}
.main {
	padding: 0 30rpx;
	margin-top: 20rpx;
	.button {
		height: 89rpx;
		background: #ff4400;
		border-radius: 44rpx 44rpx 45rpx 45rpx;
		line-height: 89rpx;
		text-align: center;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 36rpx;
		color: #ffffff;
	}
}
.goods {
	background: #ffffff;
	border-radius: 14rpx;
	padding: 30rpx 20rpx 0 30rpx;
	&-title {
		font-family: 'PingFang SC';
		font-weight: 500;
		font-size: 30rpx;
		color: #333333;
	}
	&-line {
		height: 2rpx;
		background: #fafafa;
		border-radius: 1rpx;
		margin: 22rpx 0;
	}
	&-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: 50rpx;
		&-label {
			font-family: 'PingFang SC';
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
		}
		&-value {
			font-family: 'PingFang SC';
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
		}
		&-box {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			&-item {
				padding: 5rpx 10rpx;
				background: rgba(192, 192, 192, 0.23);
				border-radius: 10rpx;
				font-family: 'PingFang SC';
				font-weight: 500;
				font-size: 28rpx;
				color: #999999;
				margin-left: 20rpx;
			}
			&-active {
				font-family: 'PingFang SC';
				font-weight: 500;
				font-size: 28rpx;
				color: #ff0000;
				background: rgba(255, 0, 0, 0.1);
				border-radius: 10rpx;
			}
		}
	}
}
.rentalPlan {
	background: #ffffff;
	border-radius: 14rpx;
	padding: 30rpx 20rpx 25rpx 30rpx;
	margin: 30rpx 0 20rpx;
	&-title {
		font-family: 'PingFang SC';
		font-weight: 500;
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 40rpx;
	}
	&-item {
		display: flex;
		align-items: center;
		height: 105rpx;
		border-top: 2rpx solid #f1f1f1;
		box-sizing: border-box;
		&-left {
			height: 100%;
			width: 35%;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			padding-left: 10rpx;
			font-family: 'PingFang SC';
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
		}
		&-right {
			height: 100%;
			border-left: 2rpx solid rgba(227, 227, 227, 0.5);
			width: 65%;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			justify-content: center;
			font-family: 'PingFang SC';
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
		}
	}
	&-item_ {
		background-color: #f1f1f1;
		&-left {
			padding-left: 20rpx;
		}
		&-right {
			border-left: none;
		}
	}
	&-footer {
		display: flex;
		align-items: center;
		height: 74rpx;
		background: #f1f1f1;
		border-radius: 10rpx;
		box-sizing: border-box;
		&-left {
			height: 100%;
			width: 35%;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			padding-left: 15rpx;
			font-family: 'PingFang SC';
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
		}
		&-right {
			height: 100%;
			width: 65%;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			justify-content: center;
			font-family: 'PingFang SC';
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
		}
	}
}
.precautions {
	background: #ffffff;
	border-radius: 14rpx;
	padding: 30rpx 20rpx 20rpx 30rpx;
	margin: 30rpx 0 20rpx;
	&-title {
		font-family: 'PingFang SC';
		font-weight: 500;
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 15rpx;
	}
	&-content {
		font-family: 'PingFang SC';
		font-weight: 400;
		font-size: 24rpx;
		color: #999999;
		&-item {
			margin-top: 20rpx;
		}
	}
	&-text {
		font-family: 'PingFang SC';
		font-weight: 500;
		font-size: 22rpx;
		color: #ff0000;
		margin-top: 20rpx;
	}
}
.agreement {
	font-family: 'PingFang SC';
	font-weight: 400;
	font-size: 24rpx;
	color: #999999;
	margin-bottom: 20rpx;
	&-content {
		// display: flex;
		&-icon {
			display: inline-block;
			width: 25rpx;
			height: 25rpx;
			padding: 0 10rpx 5rpx 0;
		}
		text {
			color: #ff4603;
		}
	}
}
</style>
